package com.ruix.app.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.widget.ScrollView;

/**
 * User: hadexs
 * Date: 2016-03-16
 * Time: 14:40
 */
public class MyScrollView extends ScrollView {

    private Context context;
    private float ratio;

    public MyScrollView(Context context) {
        super(context);
        init(context);
    }

    public MyScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        ratio = attrs.getAttributeFloatValue("http://schemas.android.com/apk/res-auto", "heightRatio", (float) 0.6447);
        init(context);
    }

    public MyScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        ratio = attrs.getAttributeFloatValue("http://schemas.android.com/apk/res-auto", "heightRatio", (float) 0.6447);
        init(context);
    }

    private void init(Context context) {
        this.context = context;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // TODO Auto-generated method stub
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(metrics);
        int pixelsHeight = metrics.heightPixels;
        int maxHeight = (int) (pixelsHeight * ratio);//0.6447
        final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        if (heightMode == MeasureSpec.UNSPECIFIED) {
            return;
        }
        int height = getMeasuredHeight();
        int specWidthSize = MeasureSpec.getSize(widthMeasureSpec);
        if (height > maxHeight) {
            setMeasuredDimension(specWidthSize, maxHeight);
        } else {
            setMeasuredDimension(specWidthSize, height);
        }
    }
}